<?php

/**
 * @file
 * Restrict attributes of a remote image.
 */

$plugin = array(
  'form' => 'feeds_tamper_ccloud_restrict_image_form',
  'callback' => 'feeds_tamper_ccloud_restrict_image_callback',
  'name' => 'CCloud: Restrict image attributes',
  'multi' => 'loop',
  'category' => 'HTML',
);

function feeds_tamper_ccloud_restrict_image_form($importer, $element_key, $settings) {
  $form = array();

  $form['width_min'] = array(
    '#type' => 'textfield',
    '#title' => t('Width (min)'),
    '#description' => t('Such as: 100'),
    '#default_value' => isset($settings['width_min']) ? $settings['width_min'] : '',
  );

  $form['height_min'] = array(
    '#type' => 'textfield',
    '#title' => t('Height (min)'),
    '#description' => t('Such as: 100'),
    '#default_value' => isset($settings['height_min']) ? $settings['height_min'] : '',
  );

  $form['width_max'] = array(
    '#type' => 'textfield',
    '#title' => t('Width (max)'),
    '#description' => t('Such as: 100'),
    '#default_value' => isset($settings['width_max']) ? $settings['width_max'] : '',
  );

  $form['height_max'] = array(
    '#type' => 'textfield',
    '#title' => t('Height (max)'),
    '#description' => t('Such as: 100'),
    '#default_value' => isset($settings['height_max']) ? $settings['height_max'] : '',
  );

  return $form;
}

function feeds_tamper_ccloud_restrict_image_callback($result, $item_key, $element_key, &$field, $settings, $source) {
  if (!empty($field)) {
    list($width, $height, $type, $attr) = getimagesize($field);

    $width_min = $settings['width_min'];
    $height_min = $settings['height_min'];
    $width_max = $settings['width_max'];
    $height_max = $settings['height_max'];

    if ((!empty($width_min) && $width < $width_min)
      || (!empty($width_max) && $width > $width_max)
      || (!empty($height_min) && $height < $height_min)
      || (!empty($height_max) && $height > $height_max)
    ) {
      $field = NULL;
    }
  }
}